package com.spider.moudle.factory;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.spider.moudle.constant.Constant;
import com.spider.moudle.util.CommonUtil;
import com.spider.moudle.util.DateUtil;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author 夏茂轩
 * @description 线城池工厂类, 用于定期监控多个线城池的状态, 并写入到status.log
 * @date 2017/12/8 10:42
 */
public class ExecutorServiceFactoy {
    private static final String log_file = "pool_status_";
    private static Map<String, ThreadPoolExecutor> map = Maps.newConcurrentMap();
    static {
        Thread thread = new Thread(() -> {
            while (true) {
                File file = new File(log_file+DateUtil.date_to_str(new Date(),"yyyy-MM-dd-HH")+".log");
                try {
                    Thread.sleep(Constant.STATUS_INL);
                    JSONArray a = new JSONArray();
                    for (Map.Entry<String, ThreadPoolExecutor> entry : map.entrySet()) {
                        JSONObject object = new JSONObject();
                        ThreadPoolExecutor executor = entry.getValue();
                        object.put("线程池名称", entry.getKey());
                        object.put("活跃线程数", executor.getActiveCount());
                        object.put("是否关闭", executor.isTerminated());
                        object.put("已完成任务数", executor.getCompletedTaskCount());
                        object.put("当前时间", DateUtil.date_to_str(new Date(), DateUtil.yyyy_MM_dd_HH_mm_ss));
                        if (executor.isTerminated()) {
                            map.remove(entry.getKey());
                        }
                        a.add(object);
                    }
                    FileWriter writer = new FileWriter(file, true);
                    writer.write(a.toJSONString()+"\n");
                    writer.flush();
                    writer.close();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        thread.start();
    }

    /**
     * @param [name, factory]
     * @return java.util.concurrent.ExecutorService
     * @author 夏茂轩
     * @description 创建线程吃
     * @date 2017/12/8 10:59
     */
    public static ExecutorService buildExecutorService(int size, String name, NamedThreadFactory factory) {
        factory.setFactoryName(name);
        ExecutorService service = Executors.newFixedThreadPool(size, factory);
        ThreadPoolExecutor executor = (ThreadPoolExecutor) service;
        map.put(name+"-{factory_create_time:'"+DateUtil.date_to_str(new Date(),DateUtil.yyyy_MM_dd_HH_mm_ss)+"'}", executor);
        return service;
    }

    /**
     * 根据网站名和帖子(url)生成线程池名字
     * @param name
     * @param tid
     * @return
     */
    public static String getName(String name, String tid) {
        StringBuilder builder = new StringBuilder();
        if(CommonUtil.isNull(name)) {
            name = "";
        }
        if(CommonUtil.isNull(tid)) {
            tid = "";
        }
        builder.append("{site:'")
                .append(name)
                .append("', tid:'")
                .append(tid)
                .append("',uuid:'")
                .append(UUID.randomUUID().toString().replaceAll("-", ""))
                .append("'}");
        return builder.toString();
    }
}
